#coding:utf-8
import sys

import paramiko,os,time,datetime
from termcolor import colored
import collections

from appMonitor.models import EnvironmentName,Host,Runapp,Appport
from django.http import HttpResponse

##不通过配置ssh.load_system_host_keys()本地known_hosts文件登陆[默认~/.ssh/known_hosts]
#证书登陆
hostname = '120.27.193.45'
username = 'yl'
sshPort = 7744
ylPassword = 'k@kd#$$0923*&Sd'                       # yl帐号的密码 当使用sudo 执行命令时需要
rootPassword = 'oT2vpo#a4LWBv6CXV*St'               # root帐号密码
keyPath = r'S:\new_rsa\vm\yunlai_cjds_test'       #私钥文件
keyPassword = 'PepjxU^qJ@oIsEI8$j9H'       #私钥密码
paramiko.util.log_to_file('syslogin.log')   #发送paramiko日志到syslogin.log文件

class updataServerDataClass(object):
    def __init__(self, hostname, username, sshPort, keyPath, keyPassword, usernameSudoPassword):
        self.hostname = hostname
        self.username = username
        self.sshPort = sshPort
        self.keyPath = keyPath
        self.keyPassword = keyPassword
        self.usernameSudoPassword = usernameSudoPassword

    #初始化ssh连接
    def _initSSHClient(self):
        sshClient = paramiko.SSHClient()  #创建一个ssh客户端client对象
        sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        privatekey = os.path.expandvars(self.keyPath)         #证书文件路径
        key = paramiko.RSAKey.from_private_key_file(privatekey,password=self.keyPassword)    #证书登陆时需要指定证书，密码为私钥密码
        sshClient.connect(hostname=self.hostname, username=self.username, port=self.sshPort, pkey=key)     #创建ssh连接，当使用证书登陆时须指定pkey参数
        return sshClient

    # 得到运行的java进程列表
    def getRunApp(self):
        result = []
        sshClient = self._initSSHClient()
        runApplication = []
        stdin, stdout, stderr = sshClient.exec_command('''ps -ef | grep java | egrep -v "grep|cloud" | awk -F ' ' '{print $NF}' | egrep *.jar$''')
        for i in stdout.readlines():
            #runApplication.append(i.strip())
            print (os.path.split(i.strip()))
            print (os.path.split(i.strip())[1])
            runApplication.append(os.path.split(i.strip())[1])
        print ('运行的java应用为:')
        print (len(runApplication),runApplication)        #[u'base-web-admin.jar', u'cjds-im-service-exec.jar', u'/APP/www/marketing-scratch-card-web/scratch-card-web-exec.jar', ……]

        # 得到每个应用监听的端口号(采用sudo执行 netstat -antp命令)
        applicationName = 'cjds-oms-gateway-exec.jar'
        for i in runApplication:
            print (i)
            tempDic = collections.OrderedDict()
            tempDic['runApplicationName'] = i
            cmd = "sudo netstat -antp | grep LISTEN | grep $(ps -ef | grep '%s' | grep -v 'grep' | awk -F ' ' '{print $2}') | awk -F ':' '{print $2}'| awk -F ' ' '{print $1}'" % i
            stdin,stdout,stderr = sshClient.exec_command(cmd,get_pty=True)   #调用远程执行命令方法exec_command()
            stdin.write(self.usernameSudoPassword+'\n')
            appListenPort = []
            #print stdout.readlines
            for j in stdout.readlines():
                print (j)
                if self.username not in j and self.usernameSudoPassword not in j:
                    appListenPort.append(j.strip())
            tempDic['listenPort'] = appListenPort
            print (tempDic)
            result.append(tempDic)
            print ('**'* 50)

        sshClient.close()
        return result




#得到每个应用监听的端口  先使用su - root，切换至root权限进行截取  ---已废弃
# def getAppListen(applicationName):
#     '''
#     :param applicationName: java应用的名称 如cjds-im-service-exec.jar
#     :return: ['20902', '9191', '5004']
#     '''
#     sshClient = initSSHClient()
#     cmd = "netstat -antp | grep LISTEN | grep $(ps -ef | grep '%s' | grep -v 'grep' | awk -F ' ' '{print $2}') | awk -F ':' '{print $2}'| awk -F ' ' '{print $1}'" % applicationName
#     if username != 'root':
#         ssh = sshClient.invoke_shell()
#         print ssh
#         time.sleep(0.1)
#         ssh.send('su - \n')
#         buff = ''
#         while not buff.endswith(r'Password: '):
#             resp = ssh.recv(9999)
#             buff += resp
#         print 'first buff:', buff
#         ssh.send(rootPassword)
#         ssh.send('\n')
#
#         buff = ''
#         while not buff.endswith('# '):
#             resp = ssh.recv(9999)
#             buff += resp
#         print 'second buff:', buff
#         ssh.send(cmd)
#         ssh.send('\n')
#
#         buff = ''
#         while not buff.endswith('# '):
#             resp = ssh.recv(1024)
#             buff += resp
#         ssh.close()
#
#     result = buff
#     print type(result),result
#     # for k,v in enumerate(result.split()):
#     #     print k,'===>',v
#     sshClient.close()
#     return result.split()[36:-2]


#得到进程列表以及每个进程监听的端口号  ---已废弃
# def getServerAllData():
#     result = []
#     for i in getRunApp():
#         tempDic = collections.OrderedDict()
#         tempDic['runApplicationName'] = i
#         tempDic['listenPort'] = getAppListen(i)
#         print tempDic
#         result.append(tempDic)
#     print result
#     for i in result:
#         print i
#         for k,v in i.items():
#             print k,'===>>>'
#     return result


def main(request):
    beginTime = time.time()
    print ('开始执行此函数……')
    updataServerDataObj = updataServerDataClass(hostname=hostname,username=username,sshPort=sshPort,keyPath=keyPath,keyPassword=keyPassword,usernameSudoPassword=ylPassword)
    print (updataServerDataObj.getRunApp())
    for i in updataServerDataObj.getRunApp():
        print (i['runApplicationName'],i['listenPort'])
        for k,v in i.items():
            print ('从服务器上获取到的数据清洗后的结果:',k,'===>',v)
        if len(i['listenPort']) > 0:
            for port in i['listenPort']:
                appPorts = Appport.objects.update_or_create(port=port)  #update_or_create不存在就创建记录，存在就不创建记录
                appName = Runapp.objects.update_or_create(appname=i['runApplicationName'])

                appPortsGet = Appport.objects.get(port=port)
                appNameGet = Runapp.objects.get(appname=i['runApplicationName'])
                hostGet = Host.objects.get(internetIP='120.27.193.45')
                #appNameGet.ports.clear()
                appNameGet.ports.add(appPortsGet)
                appNameGet.save()

                #hostGet.runapps.clear()
                hostGet.runapps.add(appNameGet)
                hostGet.save()
        else:
            appPorts = Appport.objects.update_or_create(port=0)
            appName = Runapp.objects.update_or_create(appname=i['runApplicationName'])

            appPortsGet = Appport.objects.get(port=0)
            appNameGet = Runapp.objects.get(appname=i['runApplicationName'])
            hostGet = Host.objects.get(internetIP='120.27.193.45')
            #appNameGet.ports.clear()        #先删除关联关系再新建
            appNameGet.ports.add(appPortsGet)
            appNameGet.save()

            #hostGet.runapps.clear()
            hostGet.runapps.add(appNameGet)
            hostGet.save()
    print ('耗时为:',time.time() - beginTime)
    return HttpResponse('<h1> test update ServerData</h1>')

#Appport.objects.bulk_create(['1001','1002'])
# getRunApp()

# getAppListen('emall-item-gateway-exec.jar')
# getAppListen('cjds-im-gateway-exec.jar')
